import { register } from './register-service-worker'

/**
 * 
 * @param {*} swUrl | '/service-worker.js'  service-worker url
 * @param {*} registrationOptions  |{ scope: '/' }
 */
export default function (swUrl, registrationOptions = { scope: '/' }) {
    register(swUrl || '/service-worker.js', {
        registrationOptions,
        parsed() {
            registerMessage()
        },
        ready(registration) {
            console.log('Service worker is active.')
        },
        registered(registration) {
            console.log('Service worker has been registered.')
            const VERSION = localStorage.getItem('VERSION');
            console.log(VERSION, VUE_APP_VERSION)
            if (!VERSION) {
                localStorage.setItem('SW_VERSION', VUE_APP_VERSION);
                return;
            }
            if (VERSION != VUE_APP_VERSION) {
                notifyInfo(registration)
            }
        },
        cached(registration) {
            console.log('Content has been cached for offline use.')
        },
        updatefound(registration) {
            console.log('New content is downloading.')
        },
        updated(registration) {
            console.log('New content is available; please refresh.')
        },
        offline() {
            console.log('No internet connection found. App is running in offline mode.')
        },
        error(error) {
            console.error('Error during service worker registration:', error)
        }
    })
}

/**
 * 绑定事件处理
 */
function registerMessage() {
    try {
        navigator.serviceWorker.addEventListener('message', function (e) {
            var action = e.data;
            if (action === 'update') {
                forceUpdate();
            }
        })
    } catch (error) {
        console.error('registerMessage:', error)
    }
}
/**
 * 手动更新registration
 */
function forceUpdate() {
    navigator.serviceWorker.getRegistration().then(registration => {
        registration.update().then(function () {
            localStorage.setItem('SW_VERSION', VUE_APP_VERSION);
            window.location.reload(true);
        });
    })
}
/**
 * 获取用户授权通知
 */
function askPermission() {
    return Notification.requestPermission().then(function (result) {
        if (result !== 'granted') {
            throw new Error('We weren\'t granted permission.');
        }
        return result;
    })
}

/**
 * 通知用户
 */
function notifyInfo(registration) {
    Promise.all([registration || navigator.serviceWorker.getRegistration(), askPermission()]).then((results) => {
        const reg = results[0];
        reg.showNotification(process.env.VUE_APP_PROJECT_TITLE, {
            body: '版本有更新',
            // data: '携带的数据',
            icon: require('../public/static/img/favicon-16x16.png'),
            // badge: '/img/icons/favicon-16x16.png',
            tag: 'VERSION',
            timestamp: Date.now(),
            actions: [{
                action: 'update',
                title: `${VUE_APP_VERSION}版本`,
                icon: require('../public/static/img/favicon-16x16.png'),
            }, {
                action: 'close',
                title: '取消更新',
                icon: require('../public/static/img/favicon-16x16.png'),
            }],
            renotify: true,
            requireInteraction: true,
        });
    }).catch(err => {
        if (Notification.permission === 'denied' && window.confirm(`是否强制更新${VUE_APP_VERSION}版本`)) {
            forceUpdate()
        }
    })
}
